package br.com.polo.contas.web.converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter("calendar")
public class CalendarConverter implements Converter {
	
	Calendar cal;
	DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String value) {
		
		try {
			Date date = formatter.parse(value);
			cal = Calendar.getInstance();
			cal.setTime(date);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}

		return cal;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object value) {
		
		cal = (Calendar) value;
		
		Date date = new Date(cal.getTimeInMillis());
		
		String data = formatter.format(date);
		
		return data;
	}

}
